package com.youdianda.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youdianda.constant.MessageConstant;
import com.youdianda.context.BaseContext;
import com.youdianda.dto.EditArticleDTO;
import com.youdianda.dto.MyArticleDTO;
import com.youdianda.dto.UserDataListDTO;
import com.youdianda.dto.YddArticleListDTO;
import com.youdianda.entity.YddArticle;
import com.youdianda.entity.YddCate;
import com.youdianda.entity.YddUserData;
import com.youdianda.mapper.YddArticleMapper;
import com.youdianda.result.Result;
import com.youdianda.service.IYddArticleService;
import com.youdianda.service.IYddCateService;
import com.youdianda.service.IYddUserDataService;
import com.youdianda.vo.ListDataVO;
import com.youdianda.vo.PageResult;
import com.youdianda.vo.UserDataListVO;
import com.youdianda.vo.YddArticleListVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sdy
 * @since 2023-05-15
 */
@Service
public class YddArticleServiceImpl extends ServiceImpl<YddArticleMapper, YddArticle> implements IYddArticleService {
    @Autowired
    private IYddCateService iYddCateService;

    /**
     * 文章详情
     *
     * @param id
     * @return
     */
    @Override
    public Result details(Integer id) {

        YddArticle yddArticle = getById(id);

        return Result.success(yddArticle);
    }

    /**
     * 文章列表-分页
     *
     * @param articleListDTO
     */
    @Override
    public Result getYddTagIPage(YddArticleListDTO articleListDTO) {
        //非空判断，判断页码和每页显示记录数量是否为空
        if (articleListDTO.getPage() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }
        if (articleListDTO.getLimit() == null) {
            return Result.error(MessageConstant.UNKNOWN_ERROR);
        }

        Page<YddArticle> page = new Page<>(Long.parseLong(articleListDTO.getPage()), Long.parseLong(articleListDTO.getLimit()));

        //条件查询
        Page<YddArticle> pageLimit = page(page, Wrappers.<YddArticle>lambdaQuery()//查询条件
                .between(articleListDTO.getEnd_time() != null && articleListDTO.getStart_time() != null, YddArticle::getCreateDate, articleListDTO.getStart_time(), articleListDTO.getEnd_time())
                .like(articleListDTO.getTitle() != null, YddArticle::getTitle, articleListDTO.getTitle())
                .eq(articleListDTO.getCateid() != null, YddArticle::getCateid, articleListDTO.getTitle()));

        //创建一个list集合封装ListDataVO
        ArrayList<ListDataVO> data = new ArrayList<>();

        //循环遍历分页出来的列表数据  添加表外关联数  cateName
        pageLimit.getRecords().forEach(yddArticle -> {
            ListDataVO listDataVO = new ListDataVO();
            BeanUtils.copyProperties(yddArticle, listDataVO);
            listDataVO.setCatename(iYddCateService.getOne(Wrappers.<YddCate>lambdaQuery().eq(YddCate::getId, listDataVO.getCateid())).getCatename());
            data.add(listDataVO);
        });


        //封装数据
        YddArticleListVO vo = YddArticleListVO.builder()
                .count((int) pageLimit.getTotal())
                .totalPages((int) pageLimit.getTotal())
                .pageSize((int) pageLimit.getPages())
                .currentPage((int) pageLimit.getCurrent())
                .data(data).build();

        return Result.success(vo);
    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @Override
    public Result deleteById(Integer id) {

        boolean removeById = removeById(id);

        return Result.success(removeById);
    }

    /**
     * 文章修改
     *
     * @param yddArticle
     * @return
     */
    @Override
    public Result upDate(YddArticle yddArticle) {

        boolean updateById = updateById(yddArticle);

        return Result.success(updateById);
    }
        @Autowired
        private IYddCateService cateService;

        @Autowired
        private IYddUserDataService yddUserDataService;


        /**
         * 文章列表-分页
         *
         * @param articleListDTO
         * @return
         */
        @Override
        public Result<YddArticleListVO> articleList (YddArticleListDTO articleListDTO){

            //创建一个page对象
            Page<YddArticle> page = new Page<>(Long.parseLong(articleListDTO.getPage()), Long.parseLong(articleListDTO.getLimit()));

            //条件查询
            Page<YddArticle> pageLimit = page(page, Wrappers.<YddArticle>lambdaQuery()//查询条件
                    .between(articleListDTO.getEnd_time() != null && articleListDTO.getStart_time() != null && articleListDTO.getEnd_time() != "" && articleListDTO.getStart_time() != "", YddArticle::getCreateDate, articleListDTO.getStart_time(), articleListDTO.getEnd_time())
                    .like(articleListDTO.getTitle() != null && articleListDTO.getTitle() != "", YddArticle::getTitle, articleListDTO.getTitle())
                    .eq(articleListDTO.getCateid() != null && articleListDTO.getCateid() != "", YddArticle::getCateid, articleListDTO.getTitle()));

            //创建一个list集合封装ListDataVO
            ArrayList<ListDataVO> data = new ArrayList<>();

            //循环遍历分页出来的列表数据  添加表外关联数  cateName
            pageLimit.getRecords().forEach(yddArticle -> {
                ListDataVO listDataVO = new ListDataVO();
                BeanUtils.copyProperties(yddArticle, listDataVO);
                listDataVO.setCatename(cateService.getOne(Wrappers.<YddCate>lambdaQuery().eq(YddCate::getId, listDataVO.getCateid())).getCatename());
                data.add(listDataVO);
            });


            //封装数据
            YddArticleListVO vo = YddArticleListVO.builder()
                    .count((int) pageLimit.getTotal())
                    .totalPages((int) pageLimit.getTotal())
                    .pageSize((int) pageLimit.getPages())
                    .currentPage((int) pageLimit.getCurrent())
                    .data(data).build();

            return Result.success(vo);
        }


        /**
         * 、
         * 我的文章a
         *
         * @param myArticleDTO
         * @return
         */
        @Override
        public Result<PageResult> myArticle (MyArticleDTO myArticleDTO){

            //1.data
            Page articlePage = new Page(Long.parseLong(myArticleDTO.getPage() + ""), Long.parseLong(myArticleDTO.getLimit() + ""));

            Page page = page(articlePage, Wrappers.<YddArticle>lambdaQuery().eq(YddArticle::getUserId, BaseContext.getCurrentId()));


            return Result.success(PageResult.builder()
                    .count((int) page.getTotal())
                    .totalPages((int) page.getPages())
                    .pageSize((int) page.getSize())
                    .currentPage((int) page.getCurrent())
                    .data(page.getRecords())
                    .build());
        }


        /**
         * 我的收藏/点赞文章
         *
         * @param userDataListDTO
         * @return
         */
        @Override
        public Result<UserDataListVO> userDataList (UserDataListDTO userDataListDTO){

            //1.根据type和userId  查询articleId
            List<YddUserData> articleIds = yddUserDataService.list(Wrappers.<YddUserData>lambdaQuery()
                    .eq(YddUserData::getUserId, BaseContext.getCurrentId())
                    .eq(YddUserData::getType, userDataListDTO.getType())
                    .select(YddUserData::getArticleId));
            List<Integer> collect = articleIds.stream().map(YddUserData::getArticleId).collect(Collectors.toList());

            //2.根据articleId查询article 的数据list
            Page<YddArticle> pageLimit = new Page<>(userDataListDTO.getPage(), userDataListDTO.getLimit());
            Page<YddArticle> page = page(pageLimit, Wrappers.<YddArticle>lambdaQuery()
                    .orderByAsc(YddArticle::getCreateDate)
                    .in(YddArticle::getCateid, collect));


            System.out.println("+++++++++++++++++" + page.getRecords() + "+++++++++++");

            //3.根据article的cateId   查询cate 封装cateName
            ArrayList<ListDataVO> arrayList = new ArrayList<>();
            page.getRecords().forEach(yddArticle -> {
                ListDataVO listDataVO = new ListDataVO();
                BeanUtils.copyProperties(yddArticle, listDataVO);
                listDataVO.setCatename(cateService.getOne(Wrappers.<YddCate>lambdaQuery().eq(YddCate::getId, yddArticle.getCateid())).getCatename());
                arrayList.add(listDataVO);
            });
            PageResult list = PageResult.builder().count((int) page.getTotal())
                    .totalPages((int) page.getTotal())
                    .pageSize((int) page.getSize())
                    .currentPage((int) page.getCurrent())
                    .data(arrayList)
                    .build();

            //4.封装数据PageResult
            return Result.success(UserDataListVO.builder()
                    .list(list)
                    .build());

//        articleIds.forEach(articleId ->{
            //根据articleId 查询YddArticle
//            List<YddArticle> list = list(Wrappers.<YddArticle>lambdaQuery().eq(YddArticle::getId, articleId));
//
//            List<YddArticle> articleList = yddArticleService.list(Wrappers.<YddArticle>lambdaQuery()
//                    .eq(YddArticle::getUserId, articleId.getArticleId()));

//        });


        }

        /**
         * 修改文章
         *
         * @param articleDTO
         * @return
         */
        @Override
        public Result editArticle (EditArticleDTO articleDTO){

            YddArticle yddArticle = new YddArticle();
            BeanUtils.copyProperties(articleDTO, yddArticle);

            updateById(yddArticle);

            return Result.success();
        }

    /**
     * 文章添加
     *
     * @param yddArticle
     * @return
     */
    @Override
    public Result add(YddArticle yddArticle) {

        yddArticle.setDefaultData("1");
        yddArticle.setCreateDate(System.currentTimeMillis());
        boolean save = save(yddArticle);
        return Result.success(save);
    }
}
